package o2o.web.actions.postman;

import com.jinyou.utils.common.*;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.agent.PostmanAgentRelationMemory;
import o2o.cache.agent.UserAgentRelationMemory;
import o2o.cache.comment.OrderCommentMemory;
import o2o.cache.company.postman.PostCompanyMemory;
import o2o.cache.company.postman.PostTypeMemory;
import o2o.cache.company.postman.PostmanSignCompanyMemory;
import o2o.cache.company.postman.PostmanTypeRelationMemory;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.postman.PostmanPositionMemory;
import o2o.cache.postman.PostmanShopRelationMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.agent.PostmanAgentRelation;
import o2o.dao.PO.agent.UserAgentRelation;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.company.postman.*;
import o2o.dao.PO.order.OrderCommentInfo;
import o2o.dao.PO.postman.*;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.dao.VO.company.postman.PostTypeInfoVO;
import o2o.dao.VO.order.OrderCommentInfoVO;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.postman.model.CityPostman;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.utils.CommonUtils;
import o2o.web.actions.company.postman.PostCompanyMan;
import org.apache.commons.lang.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

//配送员位置
public class PostmanMan {

    private static Object o = new Object();

    // 添加配送员的与配类型的关系
    public static void addPostmanTypeRelation(String postman, int type, Long tipPaotuiId, String opUser) {
        if (StringUtils.isEmpty(postman)) {
            return;
        }
        List<PostTypeInfoVO> list = PostCompanyMan.listOfPostTypeInfoByPostman(postman, type);
        if (list == null || list.isEmpty()) {
            // 添加一条
            Long ctime = DateUtils.getCurrTime();
            PostmanTypeRelationInfo relationInfo = new PostmanTypeRelationInfo();
            PostTypeInfo typeInfo = PostTypeMemory.getInstance().getByCode(type);
            if (typeInfo == null) {
                System.out.println("添加配送员类型关系失败");
            }
            relationInfo.setCreateTime(ctime).setCreateUser(opUser).setDelFlag(0).setTypeId(typeInfo.getId())
                    .setCarTipId(tipPaotuiId).setUsername(postman);
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.POSTMAN_TYPE_RELATION, relationInfo);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("添加配送员类型关系失败");
            }
            PostmanTypeRelationMemory.getInstance().load(postman);

            // 数据通讯
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_DELIVERY_TYPE_RELOAD).setStr01(postman);
            JmsSender.setTopicSender(notify);
        }
    }

    public static void addPostmanPlateCompany(String postman, String city, int type, String opUser) {

        PostTypeInfo typeInfo = PostTypeMemory.getInstance().getByCode(type);
        if (typeInfo == null) {
            return;
        }
        List<PostCompanyInfo> infos = PostCompanyMemory.getInstance().listOfCity(city, POST_COMPANY_TYPE.PLATE);
        if (infos != null && infos.size() > 0) {
            Connection con = null;
            try {
                con = UserDaoSql.getInstance().getConnection();
                con.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
                return;
            }
            Long cTime = DateUtils.getCurrTime();
            for (PostCompanyInfo info : infos) {
                PostmanSignCompanyInfo postmanSignCompanyInfo = new PostmanSignCompanyInfo();
                postmanSignCompanyInfo.setUsername(postman).setPostType(type)
                        .setMoney(0.0D).setApplyTime(cTime).setDelFlag(0).setDealTime(cTime)
                        .setCreateUser(opUser).setCreateTime(cTime)
                        .setCompanyId(info.getId()).setPostTypeId(typeInfo.getId()).setStatus(SIGN_COMPANY_STATUS.pass);
                try {
                    UserDaoSql.getInstance().saveObj(PojoTables.POSTMAN_SIGN_COMPANY, postmanSignCompanyInfo, con);
                } catch (Exception e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(con);
                }
            }
            try {
                con.commit();
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(con);
            } finally {
                UserDaoSql.getInstance().close(con);
            }
            PostmanSignCompanyMemory.getInstance().add(cTime);
            // 数据通讯
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.COMPANY_POSTMAN_SIGN_ADD).setLong01(cTime);
            JmsSender.setTopicSender(notify);
        }
    }

    /**
     * 获取服务店铺的骑手信息 通过店铺的账号获取
     *
     * @param shopUsername
     * @param isLock
     * @return
     */
    public static List<CityPostman> listPostmanByServiceShop(String shopUsername, Integer isLock) {
        List<String> pUserList = PostmanShopRelationMemory.getInstance().listShopPostManListByShopUsername(shopUsername);
        if (!ValidateUtil.isAbsList(pUserList)) {
            return Collections.emptyList();
        }
        List<CityPostman> dataList = new ArrayList<>();
        // 查询
        Set<String> postmanSet = new HashSet<String>(pUserList);
        for (String username : postmanSet) {
            //根据账号获取所有配送信息,存入，返回
            CityPostman postman = CityPostmanMemory.getInstance().getPostman(username);
            if (null == postman) {
                continue;
            }
            if (isLock - 2 != 0) {   // 0启用 1停用 2 全部
                if (isLock - postman.getIsLock() != 0) {
                    continue;
                }
            }
            //是否已认证
            if (0 != 1 - postman.getIsVerify()) {
                continue;
            }
            dataList.add(postman);
        }
        return dataList;
    }

    // 根据代理获取商圈下所有配送员
    public static List<CityPostman> listOfAgent(String username, Integer isLock) {
        if (ValidateUtil.isNull(username)) {
            return null;
        }

        //获取某城代账号下所有商圈
        List<UserAgentRelation> uAList = UserAgentRelationMemory.getInstance().listOfUsername(username);
        if (ValidateUtil.isAbsList(uAList)) {
            List<CityPostman> volist = new ArrayList<>();
            List<String> list = new ArrayList<>();
            for (int i = 0; i < uAList.size(); i++) {
                if (ValidateUtil.isNotID(uAList.get(i).getAgentId())) {
                    continue;
                }
                //根据商圈Id获取所有配送员账号
                list = PostmanAgentRelationMemory.getInstance().listOfAgentId(uAList.get(i).getAgentId());
                if (ValidateUtil.isAbsList(list)) {
                    for (int j = 0; j < list.size(); j++) {
                        if (ValidateUtil.isNull(list.get(j))) {
                            continue;
                        }
                        //根据账号获取所有配送信息,存入，返回
                        CityPostman postman = CityPostmanMemory.getInstance().getPostman(list.get(j));
                        if (null == postman) {
                            continue;
                        }
                        if (isLock - 2 != 0) {   // 0启用 1停用 2 全部
                            if (isLock - postman.getIsLock() != 0) {
                                continue;
                            }
                        }
                        //是否已认证
                        if (0 != 1 - postman.getIsVerify()) {
                            continue;
                        }
                        volist.add(postman);
                    }
                }
            }
            if (ValidateUtil.isAbsList(volist)) {
                return volist;
            }
        }
        return null;
    }

    public static void updatePostmanVerify(UserInfo user, CityPostmanVerify info, FileUploadInfo fileUploadInfo) throws Exception {
        if (null != fileUploadInfo) {
            // 用户头像
            if (null != fileUploadInfo.getImage()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage());
                if (null == filepath) {
                    throw new Exception("存储路径不能为空");
                }
                info.setImageUrl(filepath);
            }
            // 身份证照正面
            if (null != fileUploadInfo.getImage1()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage1());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl1(filepath);
            }
            // 身份证照反面
            if (null != fileUploadInfo.getImage2()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage2());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl2(filepath);
            }
            // 手持身份证
            if (null != fileUploadInfo.getImage3()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage3());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl3(filepath);
            }
            // 营业执行
            if (null != fileUploadInfo.getImage4()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage4());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl4(filepath);
            }
            // 备用字段5
            if (null != fileUploadInfo.getImage5()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage5());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl5(filepath);
            }
            // 备用字段6
            if (null != fileUploadInfo.getImage6()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage6());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl6(filepath);
            }
            // 备用字段7
            if (null != fileUploadInfo.getImage7()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage7());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl7(filepath);
            }
            // 备用字段8
            if (null != fileUploadInfo.getImage8()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage8());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
//                    return AjaxResult.errorResult("存储图片失败，请稍后再试");
                }
                info.setImageUrl8(filepath);
            }
            // 备用字段9
            if (null != fileUploadInfo.getImage9()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage9());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
                }
                info.setImageUrl9(filepath);
            }
            // 备用字段10
            if (null != fileUploadInfo.getImage10()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage10());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
                }
                info.setImageUrl10(filepath);
            }
            // 备用字段11
            if (null != fileUploadInfo.getImage11()) {
                String filepath = JYImageUtils.saveImage(SYS_CONFIG_PATH.USER_IMAGE, fileUploadInfo.getImage11());
                if (null == filepath) {
                    throw new Exception("存储图片失败，请稍后再试");
                }
                info.setImageUrl11(filepath);
            }
        }
        if (null == info.getType()) {
            info.setType(POSTMAN_TYPE.POSTMAN);
        }
        //身份证图片

        info.setCreateUser(user.getUsername());
        long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setDelFlag(0);
        info.setIsVerify(1);
        info.setVerifyStatus(POSTMAN_VERIFY_STATUS.OVER);
//            info.setUsername(username);
        // 判断是否存在配送员
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT * FROM ").append(PojoTables.POSTMAN_VERITY)
                .append(" WHERE username='").append(info.getUsername()).append("' AND delFlag = 0");

        // 修改配送员
        StringBuffer sbUpd = new StringBuffer();

        String sex = "";
        if (info.getSex() != 0) {
            sex = " , sex = " + info.getSex();
        }

        String telePhone = "";
        if (ValidateUtil.isNotNull(info.getTelephone())) {
            telePhone = " , telephone = '" + info.getTelephone() + "'";
        }

        String imageUrl1 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl1())) {
            imageUrl1 = " , imageUrl1 = '" + info.getImageUrl1() + "'";
        }

        String imageUrl2 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl2())) {
            imageUrl2 = " , imageUrl2 = '" + info.getImageUrl2() + "'";
        }

        String imageUrl3 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl3())) {
            imageUrl3 = " , imageUrl3 = '" + info.getImageUrl3() + "'";
        }

        String imageUrl4 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl4())) {
            imageUrl4 = " , imageUrl4 = '" + info.getImageUrl4() + "'";
        }

        String imageUrl5 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl5())) {
            imageUrl5 = " , imageUrl5 = '" + info.getImageUrl5() + "'";
        }

        String imageUrl6 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl6())) {
            imageUrl6 = " , imageUrl6 = '" + info.getImageUrl6() + "'";
        }

        String imageUrl7 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl7())) {
            imageUrl7 = " , imageUrl7 = '" + info.getImageUrl7() + "'";
        }

        String imageUrl8 = "";
        if (ValidateUtil.isNotNull(info.getImageUrl8())) {
            imageUrl8 = " , imageUrl8 = '" + info.getImageUrl8() + "'";
        }
        String image9 = "";// 健康证反面照
        if (ValidateUtil.isNotNull(info.getImageUrl9())) {
            image9 = ",imageUrl9='" + info.getImageUrl9() + "'";
        }
        String image10 = "";// 健康证正面照
        if (ValidateUtil.isNotNull(info.getImageUrl10())) {
            image10 = ",imageUrl10='" + info.getImageUrl10() + "'";
        }
        String image11 = "";// 骑手正面照
        if (ValidateUtil.isNotNull(info.getImageUrl11())) {
            image11 = ",imageUrl11='" + info.getImageUrl11() + "'";
        }
        String healthNo = "";// 健康证序号
        if (ValidateUtil.isNotNull(info.getHealthNo())) {
            healthNo = ",healthNo='" + info.getHealthNo() + "'";
        }
        String ownerID = "";// 身份证号
        if (ValidateUtil.isNotNull(info.getOwnerID())) {
            ownerID = ",ownerID='" + info.getOwnerID() + "'";
        }
        sbUpd.append("update ").append(PojoTables.POSTMAN_VERITY).append(" set name = ").append(info.getUsername())
                .append(sex).append(telePhone).append(imageUrl1).append(imageUrl2).append(imageUrl3).append(imageUrl4).append(imageUrl5)
                .append(imageUrl6).append(imageUrl7).append(imageUrl8)
                .append(image9).append(image10).append(image11).append(healthNo).append(ownerID)
                .append(" ,updateUser='").append(user.getUsername())
                .append("' where delFlag=0 and username='").append(info.getUsername()).append("' ");
        List<HashMap<String, Object>> list = null;
        try {
            list = UserDaoSql.getInstance().queryBySql(sb.toString());
            if (list.size() > 0) {
                UserDaoSql.getInstance().executeBySql(sbUpd.toString());
            } else {
                UserDaoSql.getInstance().insertObj(PojoTables.POSTMAN_VERITY, info);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        }
    }

    //更新配送员位置
    public static boolean updatePostmanPosition(Long postmanId, String postmanUsername, Double lat, Double lng, String city, String address) {
        if (ValidateUtil.isNotID(postmanId)) {
            return false;
        }
        if (ValidateUtil.isNull(postmanUsername)) {
            return false;
        }
//        if (ValidateUtil.isNotAbsDouble(lat) || ValidateUtil.isNotAbsDouble(lng)) {
        if (ValidateUtil.isNotLatLng(lat, lng)) {
            return false;
        }

        PostmanPositionInfo rtWorkerLocalInfo = PostmanPositionMemory.getInstance().get(postmanId);
        synchronized (o){
            if (null == rtWorkerLocalInfo) { //没有该配送员信息 存入数据库
                StringBuilder sb = new StringBuilder();
                sb.append("insert into ").append(PojoTables.POSTMAN_POSITION_INFO).append(" (postmanId,postmanUsername,city,lat,lng,address,createTime,isWork) values(").append(postmanId)
                        .append(",'").append(postmanUsername).append("','").append(city).append("',").append(lat).append(",").append(lng)
                        .append(",'").append(address).append("',").append(DateUtils.getCurrTime()).append(",1)");
                try {
                    UserDaoSql.getInstance().executeBySql(sb.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            //更新配送员的位置信息
            PostmanPositionMemory.getInstance().updateLocal(postmanId, postmanUsername, "", city, "", address, lat, lng);
        }
        return true;
    }


    //获取一条
    public static CityPostmanVO getOne(CityPostman cityPostman) {
        if (null == cityPostman) {
            return null;
        }
        if (ValidateUtil.isNull(cityPostman.getUsername())) {
            return null;
        }
        UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(cityPostman.getUsername());
        if (null == userInfo) {
            return null;
        }
        CityPostmanVO cityPostmanVo = new CityPostmanVO();
        try {
            ObjectUtils.copyPropertiesExclude(userInfo, cityPostmanVo, null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        cityPostmanVo.setIsCert(userInfo.getIsCert());
        cityPostmanVo.setIsWork(cityPostman.getIsWork());
        cityPostmanVo.setId(cityPostman.getId());
        cityPostmanVo.setIsVerify(cityPostman.getIsVerify());
        cityPostmanVo.setVerifyTime(cityPostman.getVerifyTime());
        cityPostmanVo.setVerifyEndTime(cityPostman.getVerifyEndTime());
        cityPostmanVo.setLevel(cityPostman.getLevel());
        cityPostmanVo.setScore(cityPostman.getScore());
        cityPostmanVo.setType(cityPostman.getType());

        if (ValidateUtil.isNotNull(cityPostmanVo.getSignPhoto()) && ValidateUtil.isNotNetUrl(cityPostmanVo.getSignPhoto())) {
//            cityPostmanVo.setSignPhoto(Common.imageUrl + cityPostmanVo.getSignPhoto());
            cityPostmanVo.setSignPhoto(SYS_CONFIG_PATH.IMAGE_BASE_URL + cityPostmanVo.getSignPhoto());
        }

        return cityPostmanVo;
    }


    public static List<OrderCommentInfoVO> listOfPostmanAndStr(String postman, Integer str) {
        if (ValidateUtil.isNull(postman)) {
            return null;
        }
        List<OrderCommentInfo> orderCommentInfoList = OrderCommentMemory.getInstance().listByPostmanUsername(postman);
        if (ValidateUtil.isAbsList(orderCommentInfoList)) {
            for (OrderCommentInfo orderCommentInfo : orderCommentInfoList) {
                if (ValidateUtil.isNotAbsInteger(orderCommentInfo.getStar())) {
                    orderCommentInfo.setStar(0);
                }
            }
            List<OrderCommentInfo> list = new ArrayList<>();
            for (OrderCommentInfo orderCommentInfo : orderCommentInfoList) {
                if (str == null) {
                    list.add(orderCommentInfo);
                } else {
                    // 大于三颗星为好评
                    if (str == 1 && orderCommentInfo.getStar() > 3) {
                        list.add(orderCommentInfo);
                    } else if (str == 2 && orderCommentInfo.getStar() <= 3) {
                        //差评
                        list.add(orderCommentInfo);
                    }
                }
            }
            if (ValidateUtil.isAbsList(list)) {
                // 排序
                list.sort((OrderCommentInfo u1, OrderCommentInfo u2) -> u2.getId().compareTo(u1.getId()));
                List<OrderCommentInfoVO> commentInfoVOList = new ArrayList<>();
                for (OrderCommentInfo orderCommentInfo : list) {
                    if (orderCommentInfo == null) {
                        continue;
                    }
                    OrderCommentInfoVO orderCommentInfoVO = new OrderCommentInfoVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(orderCommentInfo, orderCommentInfoVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    // 处理图片
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage1Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage1Url())) {
                        orderCommentInfoVO.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage1Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage2Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage2Url())) {
                        orderCommentInfoVO.setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage2Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage3Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage3Url())) {
                        orderCommentInfoVO.setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage3Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getImage4Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getImage4Url())) {
                        orderCommentInfoVO.setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getImage4Url());
                    }
                    // 申诉图片
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage1Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage1Url())) {
                        orderCommentInfoVO.setApplyImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage1Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage2Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage2Url())) {
                        orderCommentInfoVO.setApplyImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage2Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage3Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage3Url())) {
                        orderCommentInfoVO.setApplyImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage3Url());
                    }
                    if (ValidateUtil.isNotNull(orderCommentInfoVO.getApplyImage4Url()) && ValidateUtil.isNotNetUrl(orderCommentInfoVO.getApplyImage4Url())) {
                        orderCommentInfoVO.setApplyImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + orderCommentInfoVO.getApplyImage4Url());
                    }
                    commentInfoVOList.add(orderCommentInfoVO);
                }
                return commentInfoVOList;
            }
        }
        return null;
    }


    // 修改配送员上班状态
    public static ResultInfo cityPostmanStatusModify(String username, Integer isWork) {

        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.CityPostman).append(" set isWork = ").append(isWork).append(",updateUser = '")
                .append(username).append("' where username = '").append(username).append("' and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("修改失败，请稍后再试");
//            return AjaxResult.errorResult("修改失败，请稍后再试");
        }
        CityPostmanMemory.getInstance().setIsWork(username, isWork);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_WORK_SET).setStr01(username).setInt01(isWork);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }
        return new ResultInfo();
    }


    // 添加商圈与骑手之间的关系
    public static ResultInfo dealPostmanAgentRelation(CityPostman cityPostman, String agentIds) {
        if (cityPostman == null) {
            return new ResultInfo("骑手账号不能为空");
        }
        // 需要处理的agentid
//        List<Long> list = PostmanMan.strToList(agentIds);
        // 需要处理的agentid
        Set<Long> set = CommonUtils.splitToSet(agentIds, Long.class);
        List<Long> list = set == null ? null : new ArrayList<>(set);
        // 获取商圈的agentid
        List<Long> agentIdListDB = PostmanAgentRelationMemory.getInstance().listOfAgentIdByPostman(cityPostman.getUsername());
        // 删除的 agentid
        List<Long> delList = new ArrayList<>();
        // 添加 agentid
        List<Long> addList = new ArrayList<>();

        if (ValidateUtil.isAbsList(agentIdListDB)) {
            if (list == null || list.size() == 0) {
                delList.addAll(agentIdListDB);
            } else {
                // 需要删除的
                for (Long agentId : agentIdListDB) {
                    if (!isIdInList(agentId, list)) {
                        delList.add(agentId);
                    }
                }
                // 需要添加的
                for (Long agentId : list) {
                    if (!isIdInList(agentId, agentIdListDB)) {
                        addList.add(agentId);
                    }
                }
            }
        } else {
            // 所有的都去添加
            if (list != null && list.size() > 0) {
                addList.addAll(list);
            }
        }

        // 不需要处理
        if (delList.size() == 0 && addList.size() == 0) {
            return new ResultInfo();
        }
        // 使用事务进行处理
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
        }
        // 删除之前的
        if (delList != null && delList.size() > 0) {
            StringBuffer delSql = new StringBuffer();
            delSql.append("update ").append(PojoTables.POSTMAN_AGENT_RELATION)
//                    .append(" set delFlag = 1 where postmanUsername =").append(cityPostman.getUsername()).append(" and agentId in ").append(listToString(delList));
                    .append(" set delFlag = 1 where postmanUsername =").append(cityPostman.getUsername()).append(" and agentId in ")
                    .append(" (").append(StringUtils.join(delList, ",")).append(") ");
            try {
                UserDaoSql.getInstance().executeBySql(delSql.toString(), conn);
            } catch (Exception e) {
                e.printStackTrace();
                UserDaoSql.getInstance().rollback(conn);
                UserDaoSql.getInstance().close(conn);
                return new ResultInfo("处理失败，请稍后重试V1");
            }
        }
        long cTime = DateUtils.getCurrTime();
        if (addList.size() > 0) {
            for (Long id : addList) {
                if (id == null) {
                    continue;
                }
                CityAgent cityAgent = CityAgentMemory.getInstance().getById(id);
                if (cityAgent == null) {
                    continue;
                }
                PostmanAgentRelation relation = new PostmanAgentRelation();
                relation.setAgentId(id);
                relation.setAgentUsername(cityAgent.getUsername());
                relation.setPostmanUsername(cityPostman.getUsername());
                if (null != cityPostman) {
                    relation.setPostmanId(cityPostman.getId());
                }
                relation.setCreateTime(cTime);
                relation.setDelFlag(0);
                relation.setProvince(cityPostman.getProvince());
                relation.setCity(cityPostman.getCity());
                relation.setCounty(cityPostman.getCounty());

                try {
                    UserDaoSql.getInstance().saveObj(PojoTables.POSTMAN_AGENT_RELATION, relation, conn);
                } catch (SQLException e) {
                    e.printStackTrace();
                    UserDaoSql.getInstance().rollback(conn);
                    return new ResultInfo("条件代理关系时失败，请稍后再试V1");
                }
            }
        }
        try {
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
        } finally {
            UserDaoSql.getInstance().close(conn);
        }

        // 缓存处理
        // 添加
        if (addList.size() > 0) {
            PostmanAgentRelationMemory.getInstance().addByCreateTime(cTime);
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_ADD_BY_TIME).setLong01(cTime);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }

        }
        // 删除
        if (delList.size() > 0) {
            for (Long id : delList) {
                PostmanAgentRelationMemory.getInstance().delete(id, cityPostman.getUsername());
                // 数据同步
                try {
                    JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_DELETE).setLong01(id).setStr01(cityPostman.getUsername());
                    JmsSender.setTopicSender(notify);
                } catch (Exception e) {
                }

            }
        }
        return new ResultInfo();
    }

    // 根据骑手获取服务的商圈信息
    public static ResultInfo listCityAgentByPostmanService(CityPostman cityPostman) {
        if (cityPostman == null) {
            return new ResultInfo("骑手信息不能为空");
        }
        List<Long> agentIdList = PostmanAgentRelationMemory.getInstance().listOfAgentIdByPostman(cityPostman.getUsername());
        if (!ValidateUtil.isAbsList(agentIdList)) {
            return new ResultInfo();
        }
        List<CityAgentVO> list = new ArrayList<>();
        for (Long agentId : agentIdList) {
            if (ValidateUtil.isNotID(agentId)) {
                continue;
            }
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(agentId);
            if (cityAgent != null) {
                CityAgentVO cityAgentVO = new CityAgentVO();
                try {
                    ObjectUtils.copyPropertiesExclude(cityAgent, cityAgentVO);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                list.add(cityAgentVO);
            }
        }
        ResultInfo result = new ResultInfo();
        if (ValidateUtil.isAbsList(list)) {
            result.setObj(list);
        }
        return result;
    }


    // 判断指定id是不是子啊指定的里面
    private static boolean isIdInList(Long id, List<Long> list) {
        if (id == null || list == null || list.size() == 0) {
            return false;
        }
        for (Long tempId : list) {
            if (tempId.longValue() - id.longValue() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * -------------------
     */
    // 删除骑手
    public static ResultInfo delPostman(String username, String city, String opUsername) {
        if (ValidateUtil.isNull(username)) {
            return new ResultInfo("账号不能为空");
        }
        if (ValidateUtil.isNull(city)) {
            // 根据骑手账号，获取骑手信息
            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(username);
            if (null == cityPostman) {
                return new ResultInfo();
            }
            city = cityPostman.getCity();
        }

//        String users = usernames.replace(",", "','");
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.CityPostman).append(" set delFlag = 1,updateUser = '").append(opUsername).append("' where delFlag = 0 and username = '").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("删除失败，请稍后再试");
        }

        //  删除postman_verify表中的数据
        StringBuffer sb2 = new StringBuffer();
        sb2.append("update ").append(PojoTables.POSTMAN_VERITY).append(" set delFlag = 1").append(" where delFlag = 0 and username = '").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb2.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("删除2失败，请稍后再试.");
        }

        //在缓存中删除
        CityPostmanMemory.getInstance().reloadCity(city);
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.POSTMAN_RELOAD_BY_CITY).setStr01(city);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        // 删除配送员与商圈的关系
        StringBuffer sb3 = new StringBuffer();
        sb3.append("update ").append(PojoTables.POSTMAN_AGENT_RELATION).append(" set delFlag = 1").append(" where delFlag = 0 ")
                .append(" and postmanUsername ='").append(username).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb3.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ResultInfo("删除3失败，请稍后再试.");
        }
        Long agentId = PostmanAgentRelationMemory.getInstance().getAgentByPostmanUsername(username);
        if (ValidateUtil.isID(agentId)) {
            PostmanAgentRelationMemory.getInstance().reloadByAgentId(agentId);
            // 数据同步
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.AGENT_POSTMAN_RELATION_RELOAD_BY_AGENT).setLong01(agentId);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }
        }

        return new ResultInfo();
    }


    // 查看骑手是否有某种类型
    public static void postmanHasCarTip(String username, Map<String, Set<Long>> carTipIdMap) {
        List<PostmanTypeRelationInfo> relationInfos = PostmanTypeRelationMemory.getInstance().listPostTypeRelationByUsername(username);
        if (!ValidateUtil.isAbsList(relationInfos)) {
            return;
        }
        Set<Long> set = new HashSet<>();
        if (null != carTipIdMap.get(username)) {
            set.addAll(carTipIdMap.get(username));
        }
        boolean isFlag = false;
        for (PostmanTypeRelationInfo info : relationInfos) {
            set.add(info.getCarTipId());
        }
        carTipIdMap.put(username, set);
    }


    /**
     * 判断骑手是否有订单
     *
     * @return
     */
    public static boolean postmanHasOrder(String postmanUser) {
        StringBuilder sql = new StringBuilder();
        sql.append(" select count(1) as counts from ").append(PojoTables.OrderInfo)
                .append(" as OI WHERE OI.delFlag = 0 ").append(" and (postManUsername ='").append(postmanUser).append("' or secondaryPostManUsername ='").append(postmanUser).append("'").append(")");
        long count = 0;
        try {
            count = UserDaoSql.getInstance().getCount(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ValidateUtil.isAbsLong(count);
    }

}
